<template>
  <div class="app-container fullscreen">
    <div class="headBar">
      <img src="@/assets/images/njHead.png" alt="" />
      <div class="headName">
        农场数字地图
      </div>
    </div>
    <div class="container">
      <div id="left">
        <div class="box">
          <div class="title">农场总体介绍</div>
          <a
            target="_blank"
            class="boxContent"
            style="display: block; height: 210px; padding: 0 14px; color: white; line-height: 1.6; text-indent: 32px; letter-spacing: 2px;"
          >
            {{farmDesc}}
          </a>
        </div>
        <div class="box">
          <div class="title">
            智能农机管理平台
          </div>
          <div class="boxContent">
            <pillarCharts height="180px" :chart-data="chartData"></pillarCharts>
          </div>
        </div>
        <div class="box">
          <div class="title">
            农机数据统计
          </div>
          <div class="boxContent">
            <pillarChartsTwo height="350px" :chart-data="chartData"></pillarChartsTwo>
          </div>
        </div>
      </div>
      <div id="center" :class="centerClass">
        <map-gis ref="map" @init="mapInit" />
      </div>
      <div v-show="rightShow" id="right">
        <div class="box">
          <div class="title">
            农机监测
          </div>
          <div class="boxContent">
            <ProgressYuan color="#30cb13" text="在线" :value="onLineCount" :deg-num="(3 / 7) * 180" background-yuan="#051547" />
            <ProgressYuan color="#d02458" text="离线" :value="offLineCount" :deg-num="(4 / 7) * 180" background-yuan="#051547" />
            <ProgressYuan color="#ffdc4c" text="预警" :value="0" :deg-num="0" background-yuan="#051547" />
          </div>
        </div>
        <div class="box">
          <div style="position:absolute;right:32px;top:20px;color: #fff;font-size: 16px;">二号地块</div>
          <div class="title">
            土壤监测
          </div>
          <div class="boxContent">
            <el-carousel height="132px" :interval="10e3" indicator-position="none">
              <el-carousel-item v-for="i in 4" :key="i">
                <div class="list">
                  <div class="listItem">
                    <img src="@/assets/images/trwd.png" alt="" />
                    <div>
                      <div class="top">土壤温度</div>
                      <div class="num">{{ weather ? weather['SoilTemp' + i] : 26.3 }}℃</div>
                    </div>
                  </div>
                  <div class="listItem">
                    <img src="@/assets/images/trsd.png" alt="" />
                    <div>
                      <div class="top">土壤湿度</div>
                      <div class="num">{{ weather ? weather['SoilHum' + i] : 79.1 }}%</div>
                    </div>
                  </div>
                  <div class="listItem">
                    <img src="@/assets/images/trph.png" alt="" />
                    <div>
                      <div class="top">土壤PH</div>
                      <div class="num">{{ weather ? weather.PH : 8.0 }}</div>
                    </div>
                  </div>
                  <div class="listItem">
                    <img src="@/assets/images/trdd.png" alt="" />
                    <div>
                      <div class="top">土壤导电率</div>
                      <div class="num">us/cm</div>
                    </div>
                  </div>
                </div>
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
        <div class="box">
          <div class="title">
            气象监测
          </div>
          <div class="boxContent">
            <div class="list">
              <div class="listText">
                <div class="top">空气温度</div>
                <span class="num">{{ weather ? weather.Etemperature : 26.8 }}℃</span>
              </div>
              <div class="listText">
                <div class="top">空气湿度</div>
                <span class="num">75.7%RH</span>
              </div>
              <div class="listText">
                <div class="top">风向</div>
                <span class="num">{{ weather ? weather.WindDirection : 75.7 }}°</span>
              </div>
              <div class="listText">
                <div class="top">风速</div>
                <span class="num">{{ weather ? weather.WindSpeed : 3.5 }}M/S</span>
              </div>
              <div class="listText">
                <div class="top">光照</div>
                <span class="num">39630LUX</span>
              </div>
              <div class="listText">
                <div class="top">总辐射</div>
                <span class="num">{{ weather ? weatherData.temp : 0}}</span>
              </div>
              <div class="listText">
                <div class="top">气压</div>
                <span class="num">{{ weather ? weather.AirPressure : 1007.0 }}HPA</span>
              </div>
              <div class="listText">
                <div class="top">降水量</div>
                <span class="num">{{ weather ? weather.RainAdd : weatherData.precip }}mm</span>
              </div>
              <div class="listText">
                <div class="top">PM2.5</div>
                <span class="num">{{ weather ? weather.PM25 : 31 }}ug/m3</span>
              </div>
              <div class="listText">
                <div class="top">PM10</div>
                <span class="num">{{ weather ? weatherData.temp : 0 }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="box">
          <div class="title">
            害虫排名
          </div>
          <div class="boxContent" style="height:236px">
            <ListProgress height="200px"></ListProgress>
          </div>
        </div>
      </div>

    </div>
    <div
      v-if="device"
      class="popover-wrapper"
      @click="device = null;
              deviceMark.setIcon(deviceMark.eqIcon)"
    >
      <div ref="popoverDevice" class="popover" @click.stop="">
        <div class="popover-title">{{ device.eq_type }}</div>
        <div class="popover-content">
          <div>
            农机制造编号:
            <router-link :to="'../A1/equipmentDetial/detail/' + device.eq_code">
              <div style="display: inline;text-decoration: underline;color: blue;cursor: pointer;">{{ device.eq_code }}</div>
            </router-link>
          </div>
          <div>车辆类型: {{ device.eq_module }}</div>
          <div>当前状态: {{ device.online ? '在线' : '离线' }}</div>
        </div>
      </div>
    </div>
    <div v-if="field" class="popover-wrapper" @click="field = null">
      <div ref="popoverField" class="popover" @click.stop="">
        <div class="popover-title">{{ field.field_name }}</div>
        <div class="popover-content">
          <div>农场: {{ field.farm_name }}</div>
          <div>面积: {{ field.field_area }}</div>
          <div>编号: {{ field.field_code }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/** 农场数字地图 */
import { getDeviceList, getEqLdsDataByDealer } from '@/api/device'
import { getFieldList } from '@/api/farm'
import { getDailyUV, gridWeather } from '@/api/weather.js'
import { getWorkAreaChart } from '@/api/data.js'
import { getWeather } from '@/api/weather'
import { getFarmDesc } from '@/api/jf/farmBase'

import MapGis from '@/components/MapGis'
import ProgressYuan from '../../../components/ProgressYuan/index.vue'
import ListProgress from '../../components/ListProgress'
import pillarCharts from './pillarCharts.vue'
import pillarChartsTwo from './pillarChartsTwo.vue'
import coordtransform from 'coordtransform'


import { mapGetters } from 'vuex'
import onlineMark from '@/assets/images/tractor.svg'
import offlineMark from '@/assets/images/tractor_gray.svg'

export default {
  components: {
    ProgressYuan,
    MapGis,
    pillarCharts,
    pillarChartsTwo,
    ListProgress
  },
  data() {
    return {
      farmDesc: null,
      chartData: {},
      onlineMark: onlineMark,
      offlineMark: offlineMark,
      weatherData: {},
      weather: {},
      uvData: {},
      deviceList: null,
      fieldList: null,
      farmList: null,
      device: null,
      deviceMark: null,
      field: null,
      fieldMark: null,
      onLineCount: 0,
      offLineCount: 0,
      centerClass: 'centerAndRight',
      rightShow: false,
      coordtransform
    }
  },
  computed: {
    // weather() {
    //   return this.$root.weather || {}
    // }
    ...mapGetters([
      'user'
    ])
  },
  created() {
    // this.$root.setWeather()
    this.timer = setInterval(this.getDeviceList, 5 * 60 * 1000)
    // 默认加载图表数据
    this.loadChartData(null)

    this.farmDesc = this.user.farmDesc
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    async loadChartData(farmId) {
      const params = {}
      if (farmId) { params.dealer_id = farmId }
      this.chartData = await getWorkAreaChart(params)
      console.log('chartData', this.chartData)
    },
    getDeviceList() {
      getDeviceList().then(r => (this.deviceList = r))
    },
    getFarmDescription(farmId) {
      getFarmDesc(farmId).then(r => {
        if(r.code ===1){
          this.farmDesc = r.data
        }else{
          this.farmDesc = this.user.farmDesc
        }
      })
    },
    gridWeather() {
      return Promise.all([getDailyUV('120.55,31.22', 5), gridWeather('120.55,31.22')]).then(([uvRes, weatherRes]) => {
        this.weatherData = weatherRes.data.now
        this.uvData = uvRes.data.daily[0]
      })
    },
    getFarmDes(){

    },
    async mapInit(AMap, map) {
      this.deviceList = await getDeviceList()
      const fieldInfo = await getFieldList()
      console.log('fieldInfo', fieldInfo)
      this.fieldList = fieldInfo.fieldList
      this.farmList = fieldInfo.farmList
      const { Marker } = AMap

      // 农场数量聚合显示  开始==========================================
      var farmPoints = fieldInfo.farmList
      var farmCount = farmPoints.length

      var clusterIndexSet = {
        province: {
          minZoom: 2,
          maxZoom: 7
        },
        city: {
          minZoom: 7,
          maxZoom: 9
        },
        district: {
          minZoom: 9,
          maxZoom: 11
        },
        township: {
          minZoom: 11,
          maxZoom: 13
        },
        name: {
          minZoom: 13,
          maxZoom: 22
        }
      }

      function getStyle(context) {
        var clusterData = context.clusterData // 聚合中包含数据
        var index = context.index // 聚合的条件
        var count = context.count // 聚合中点的总数
        var marker = context.marker // 聚合绘制点 Marker 对象
        var color = [
          '139,101,8',
          '8,60,156',
          '66,130,198',
          '107,174,214',
          '78,200,211'
        ]
        var indexs = ['province', 'city', 'district', 'township', 'name']
        var i = indexs.indexOf(index['mainKey'])
        var text = clusterData[0][index['mainKey']]
        var size = 50
        if (i <= 3) {
          var extra = '<span class="showCount">' + context.count + '</span>'
          text = '<span class="showName">' + text + '</span>'
          text = text + extra
          var style = {
            bgColor: 'rgba(' + color[i] + ',.8)',
            borderColor: 'rgba(' + color[i] + ',1)',
            text: text,
            size: size,
            index: i,
            color: '#ffffff',
            textAlign: 'center',
            boxShadow: '0px 0px 5px rgba(0,0,0,0.8)'
          }
          return style
        } else {
          size = 12 * text.length + 20
          var style = {
            bgColor: 'rgba(' + color[i] + ',.8)',
            borderColor: 'rgba(' + color[i] + ',1)',
            text: text,
            size: size,
            index: i,
            color: '#ffffff',
            textAlign: 'center',
            boxShadow: '0px 0px 5px rgba(0,0,0,0.8)'
          }
          return style
        }
      }
      function getPosition(context) {
        var key = context.index.mainKey
        var dataItem = context.clusterData && context.clusterData[0]
        var districtName = dataItem[key]
        return null
        // if(!district[districtName]) {
        //   return null;
        // }
        // var center = district[districtName].center.split(',');
        // var centerLnglat = new AMap.LngLat(center[0], center[1]);
        // return centerLnglat;
      }
      // 自定义聚合点样式
      const _this = this
      function _renderClusterMarker(context) {
        var clusterData = context.clusterData // 聚合中包含数据
        var index = context.index // 聚合的条件
        var count = context.count // 聚合中点的总数
        var marker = context.marker // 聚合点标记对象
        var styleObj = getStyle(context)
        // 自定义点标记样式
        var div = document.createElement('div')
        if (styleObj.index <= 3) {
          div.className = 'amap-cluster'
          div.style.backgroundColor = styleObj.bgColor
          div.style.width = styleObj.size + 'px'
          div.style.height = styleObj.size + 'px'
          // 自定义点击事件
          context.marker.on('click', function(e) {
            var curZoom = map.getZoom()
            if (curZoom < 20) {
              curZoom += 2
            }
            map.setZoomAndCenter(curZoom, e.lnglat)
          })
          div.style.border = 'solid 1px ' + styleObj.borderColor
          div.style.borderRadius = styleObj.size + 'px'
          div.innerHTML = styleObj.text
          div.style.color = styleObj.color
          div.style.textAlign = styleObj.textAlign
          div.style.boxShadow = styleObj.boxShadow
        } else {
          // 最后一层不进行显示了
        }
        context.marker.setContent(div)
        // 自定义聚合点标记显示位置
        var position = getPosition(context)
        if (position) {
          context.marker.setPosition(position)
        }
        context.marker.setAnchor('center')
      }

      var cluster = new AMap.IndexCluster(map, farmPoints, {
        renderClusterMarker: _renderClusterMarker,
        clusterIndexSet: clusterIndexSet
      })
      console.log('cluster', cluster)
      // 农场数量聚合显示  结束==========================================

      // 显示农场标记点
      const farmIcon = require('../../../assets/images/farm.png')
      const farmMarkerList = this.farmList.map(
        farm => {
          const marker = new Marker({
            map,
            visible: false,
            position: [farm.longitude, farm.latitude],
            title: `${farm.code}-${farm.name}`,
            icon: farmIcon,
            anchor: 'top-center'
          })
          const _this = this
          marker.on('click', async(mk) => {
            // 加载图表数据
            _this.loadChartData(farm.id)
            //获取农场描述
            _this.getFarmDescription(farm.id)

            _this.weather =  await getWeather(farm.id)

             console.log("_this.weather",_this.weather);
            console.log("_this.rightShow",_this.rightShow);

            if (_this.rightShow) {
              console.log("xxxxxxxxxxxxxx")
              _this.rightShow = false

              _this.centerClass = 'centerAndRight'
            } else {
              // 有气象数据才显示,否则不显示
              if (_this.weather) {
                // 获取农机离线在线数据
                const param = {}
                param.farmId = farm.id
                // console.log('param', param)
                const onlineData = await getEqLdsDataByDealer(param)
                // console.log('onlineData', onlineData)
                _this.onLineCount = onlineData.online_count
                _this.offLineCount = onlineData.offline_count
                _this.rightShow = true
                _this.centerClass = 'center'
                console.log(_this)
              }else{
                _this.rightShow = false
                _this.centerClass = 'centerAndRight'
                console.log("1222222222222222")
              }
            }
          })
          return marker
        }
      )
      // 农场标记点点击事件
      // farmMarkerList.forEach((marker, i) => {
      //   marker.on('click', (mk) => {
      //     console.log("mk",mk)
      //     if(this.rightShow){
      //       this.rightShow = false
      //       this.centerClass = "centerAndRight"
      //     }else{
      //       this.rightShow = true
      //       this.centerClass = "center"
      //     }
      //   })
      // })

      // const online = require('../DigitalMap/tractor.svg')
      // const offline = require('../DigitalMap/tractor_gray.svg')

      // 创建一个 Icon
      // var eqIcon = new AMap.Icon({
      //   // 图标尺寸
      //   size: new AMap.Size(709, 349),
      //   // 图标的取图地址
      //   image: '../../../assets/images/eq1_blue.png',
      //   // 图标所用图片大小
      //   // imageSize: new AMap.Size(709, 349),
      //   // 图标取图偏移量
      //   imageOffset: new AMap.Pixel(-9, -3)
      // });

      const eqIcon1a = require('../../../assets/images/eq1_a.png')
      const eqIcon2a = require('../../../assets/images/eq2_a.png')
      const eqIcon3a = require('../../../assets/images/eq3_a.png')
      const eqIcon4a = require('../../../assets/images/eq4_a.png')
      const eqIcon1b = require('../../../assets/images/eq1_b.png')
      const eqIcon1c = require('../../../assets/images/eq1_c.png')
      const eqIcon2b = require('../../../assets/images/eq2_b.png')
      const eqIcon2c = require('../../../assets/images/eq2_c.png')
      const eqIcon3b = require('../../../assets/images/eq3_b.png')
      const eqIcon3c = require('../../../assets/images/eq3_c.png')
      const eqIcon4b = require('../../../assets/images/eq4_b.png')
      const eqIcon4c = require('../../../assets/images/eq4_c.png')
      const eqIcon5a = require('../../../assets/images/eq5_a.png')
      const eqIcon5b = require('../../../assets/images/eq5_b.png')
      const eqIcon5c = require('../../../assets/images/eq5_c.png')
      const markerList = this.deviceList.eqList.map(
        device => {
          let eqIcon
          let eqIconActive
          if (device.eq_type == '插秧机') {
            eqIcon = device.online ? eqIcon2b : eqIcon2c
            eqIconActive = eqIcon2a
          } else if (device.eq_type == '收割机') {
            eqIcon = device.online ? eqIcon1b : eqIcon1c
            eqIconActive = eqIcon1a
          } else if (device.eq_type == '拖拉机') {
            eqIcon = device.online ? eqIcon3b : eqIcon3c
            eqIconActive = eqIcon3a
          } else if (device.eq_type == '直播机') {
            eqIcon = device.online ? eqIcon5b : eqIcon5c
            eqIconActive = eqIcon5a
          } else {
            eqIcon = device.online ? eqIcon4b : eqIcon4c
            eqIconActive = eqIcon4a
          }

          var marker = new Marker({
            map,
            visible: false,
            icon: eqIcon,
            // icon: device.online ? online : offline,
            position: this.coordtransform.wgs84togcj02(device.longitude, device.latitude),
            title: `${device.eq_type}-${device.eq_code}`
          })

          marker.on('click', () => {
            const { lng, lat } = marker.getPosition()
            const pixel = map.lngLatToContainer(new AMap.LngLat(lng, lat))
            const x = pixel.x + this.$refs.map.$el.getBoundingClientRect().x
            const y = pixel.y + this.$refs.map.$el.getBoundingClientRect().y + 180
            this.device = device
            this.$nextTick(() => {
              marker.eqIcon = marker.getIcon()
              marker.setIcon(eqIconActive)
              this.deviceMark = marker

              this.$refs.popoverDevice.style.left = x + 'px'
              this.$refs.popoverDevice.style.top = y + 'px'
            })
          })

          return marker
        }
      )

      const fieldList = this.fieldList.map(
        field => {
          console.log('field.position', field.position)
          if (field.position && field.position.length > 0) {
            return new AMap.Polygon({
              path: field.position.map(({ longitude, latitude }) => new AMap.LngLat(longitude, latitude)),
              borderWeight: 3,
              strokeColor: 'red',
              fillColor: 'red',
              cursor: 'pointer'
            })
          } else {
            return null
          }
        }
      )
      fieldList.forEach((polygon, i) => {
        if (polygon) {
          console.log('polygon', polygon)
          polygon.hide()
          polygon.on('click', () => {
            this.field = this.fieldList[i]
            const { longitude, latitude } = this.field.position[0]
            const pixel = map.lngLatToContainer(new AMap.LngLat(longitude, latitude))
            const x = pixel.x + this.$refs.map.$el.getBoundingClientRect().x
            const y = pixel.y + this.$refs.map.$el.getBoundingClientRect().y
            this.$nextTick(() => {
              this.$refs.popoverField.style.left = x + 'px'
              this.$refs.popoverField.style.top = y + 'px'
            })
          })
          map.add(polygon)
        }
      })

      console.log(fieldList)

      // total.on('click', () => map.setZoomAndCenter(17, [120.75360447733, 31.188957567985]))
      map.on('zoomend', ({ target }) => {
        if (target.getZoom() > 9) {
          fieldList.forEach(polygon => {
            if (polygon) { polygon.show() }
          })
          markerList.forEach(marker => marker.show())
          farmMarkerList.forEach(marker => marker.show())
        } else {
          fieldList.forEach(polygon => {
            if (polygon) { polygon.hide() }
          })
          markerList.forEach(marker => marker.hide())
          farmMarkerList.forEach(marker => marker.hide())
        }
      })
      //如果账号下有农场，就直接定位到它
      if(this.farmList.length >0){
        map.setZoomAndCenter(12, this.farmList[0].lnglat)
        console.log("farmMarkerList",farmMarkerList)
        // farmMarkerList[0].emit("click")
      }

    }
  }
}

</script>

<style lang="scss" scoped>

.app-container {
  //width: 1920px;
  //height: 1080px;
  width: 100%;
  height: 100%;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  background: #000429;
  .container {
    width: 100%;
    height: calc(100% - 144px);
    display: flex;
    justify-content: space-between;
  }
}
.headBar {
  width: 100%;
  height: 144px;
  color: #fff;
  position: relative;
  img {
    width: 100%;
  }
  .headName {
    text-align: center;
    position: absolute;
    font-size: 40px;
    left: 50%;
    top: 30%;
    transform: translate(-50%, 0);
  }
}
.box {
  width: 100%;
  padding: 6px;
  box-sizing: border-box;
  position: relative;
  margin-bottom: 10px;
  border-image-source: url(~@/assets/images/backgroundBox.png);
  border-image-slice: 40 fill;
  border-image-width: 40px;
  border-image-repeat: round;
  .boxContent {
    margin-top: 6px;
    .el-carousel {
      width: 100%;
    }
  }
  .title {
    margin: 10px 0px 0px 32px;
    display: flex;
    align-items: center;
    color: rgb(23, 202, 240);
    font-size: 22px;
    position: relative;
    font-weight: bold;
  }
  .list {
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: space-around;
    color: #fff;
    font-size: 18px;
    .listItem {
      width: 40%;
      display: flex;
      margin-top: 10px;
      img {
        width: 50px;
        height: 46px;
        margin-right: 10px;
      }
      .top {
        font-size: 20px;
        line-height: 32px;
      }
      .num {
        font-size: 24px;
        color: #a8dffa;
        line-height: 24px;
        white-space: nowrap;
      }
    }
    .listText {
      width: 40%;
      display: flex;
      align-items: center;
      line-height: 32px;
      .top {
        font-size: 20px;
      }
      .num {
        font-size: 16px;
        margin-left: 10px;
        color: #a8dffa;
      }
    }
  }
}

.centerAndRight {
  width: 75%;
}
.center {
  width: 49%;
}

#right {
  margin-top: -32px;
  width: 26%;
  .boxContent {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    padding-bottom: 20px;
  }
}

#left {
  width: 24%;
}
.popover-wrapper {
  position: fixed;
  inset: 0;
  .popover {
    position: absolute;
    background: white;
    transform: translate(-50%, -102%);
    white-space: nowrap;
    border-radius: 8px;
    .popover-title {
      font-weight: bold;
      font-size: 20px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      padding: 8px 16px;
    }
    .popover-content {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
      padding: 8px 16px;
    }
  }
}
</style>

<style>
.amap-cluster {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
  vertical-align:middle;
}
.showName {
  font-size: 12px;
}
.showCount,.showName {
  display: block;
  /*text-overflow: ellipsis;*/
  white-space: nowrap;
  overflow: hidden;
  width: 80%;
}
</style>
